(function(root){
    var Socket = require("socket.io-client");
    var Promise = require("bluebird");

    /**
     * 客户端对象
     * @param host
     * @param port
     * @param name
     * @param pin
     * @constructor
     */
    var Client = function(host,port,name,pin) {
        var self = this;
        self.url = 'http://' + host + ':' + port;
        self.name = name;
        self.pin = pin;
        self.socket = {};
        self.logined = false;
        self.equipment = ["intelBody","intelSensor","intelDoorBell","intelPatch","intelAir"];
        self.type = ["temperature", "humidity", "wind","state", "json"];
    };

    /**
     * 连接登录
     */
    Client.prototype.Start = function(){
        var self = this;
        return self
            ._Login();
    };

    /**
     * 登录
     * @returns {Promise.<boolean>}
     * @private
     */
    Client.prototype._Login = function(){
        var self = this;

        if(self.logined === -1) {   // 如果是正在连接，阻塞
            console.log("阻塞");
            return Promise.resolve(true);
        }
        if(!! self.logined) return Promise.resolve(true);

        var p = new Promise(function(resolve,reject){
            self.socket = Socket(self.url);
            var socket = self.socket;
            self.logined = -1;          // 设置成正在连接

            socket.on('connect',function(){
                self.logined = true;
                console.log('connect to server');
                socket.emit("login",{name:self.name});
                resolve(true);
            });

            socket.on("disconnect",function(){
                self.logined = false;
            });

            socket.on("error",function(){
                self.logined = false;
            });
        });

        return p;
    };

    /**
     * 向服务器发送温度
     * @param equipment 设备 intelBody,intelSensor,intelDoorBell,intelPatch,intelAir
     * @param type 种类 temperature humidity wind state json
     * @param value 数值
     * @returns {*|Promise.<TResult>}
     */
    Client.prototype.sendData = function(equipment,type,value) {
        var self = this;
        if(self.equipment.indexOf(equipment) === -1 || self.type.indexOf(type) === -1){
            throw new Error("参数错误");
        }

        return self
            ._Login()
            .then(function(){
                self
                    .socket
                    .emit(equipment, {
                        type : type,
                        value: value
                    });
            });
    };

    hub_shared.client = new Client('139.129.42.180','5000',CONFIG.name,CONFIG.pin);
    hub_shared.client.Start().then(function(){
        done();
    });
})(this);